package cn.com.ddapp.ddm.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.DrawableBar;
import com.shizhefei.view.indicator.slidebar.ScrollBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.bean.ActivityBean;
import cn.com.ddapp.ddm.bean.LimitBean;
import cn.com.ddapp.ddm.fragment.base.limittime.TimeFiveFragment;
import cn.com.ddapp.ddm.fragment.base.limittime.TimeFourFragment;
import cn.com.ddapp.ddm.fragment.base.limittime.TimeOneFragment;
import cn.com.ddapp.ddm.fragment.base.limittime.TimeThirdFragment;
import cn.com.ddapp.ddm.fragment.base.limittime.TimeTwoFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.CountDownProTimer;
import cn.com.ddapp.ddm.util.DensityUtils;
import cn.com.ddapp.ddm.util.JsonHttpNet;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.StringUtils;
import cn.com.ddapp.ddm.util.TDevice;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/8/22 0022.//限时抢购
 */
public class LimitTimeGoActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titletext)
    TextView titletext;
    @BindView(R.id.timebutton_one)
    RadioButton timebuttonOne;
    @BindView(R.id.timebutton_two)
    RadioButton timebuttonTwo;
    @BindView(R.id.timebutton_third)
    RadioButton timebuttonThird;
    @BindView(R.id.timebutton_four)
    RadioButton timebuttonFour;
    @BindView(R.id.timebutton_five)
    RadioButton timebuttonFive;
    @BindView(R.id.newRadio)
    RadioGroup newRadio;
    @BindView(R.id.tianText)
    TextView tianText;
    @BindView(R.id.shiText)
    TextView shiText;
    @BindView(R.id.fenText)
    TextView fenText;
    @BindView(R.id.mtext)
    TextView mtext;
    @BindView(R.id.limittime)
    CountDownProTimer limittime;
    @BindView(R.id.limit_out)
    TextView limit_out;
    @BindView(R.id.empty)
    EmptyLayout empty;
    @BindView(R.id.img_error_layout)
    ImageView img;

    @BindView(R.id.moretab_indicator)
    ScrollIndicatorView scrollIndicatorView;
    @BindView(R.id.moretab_viewPager)
    ViewPager viewPager;
    private TimeOneFragment timeOneFragment;
    private TimeTwoFragment timeTwoFragment;
    private TimeThirdFragment timeThirdFragment;
    private TimeFourFragment timeFourFragment;
    private TimeFiveFragment timeFiveFragment;
    private FragmentManager fragmentManager;
    private Fragment currentFragment;
    private long mDay = 0;
    private long mHour = 4;
    private long mMin = 00;
    private long mSecond = 00;
    private int h,m,curIndex1,curIndex2,curIndex3,curIndex4,curIndex5;
    private IndicatorViewPager indicatorViewPager;
    private LayoutInflater inflate;
    private int unSelectTextColor;
    private String wid;
    private String now;

    @Override
    public void initView() {
        setTitle("限时抢购");
        setTitleLeftImg(R.mipmap.back_icon, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        try {

        Date curdate = new Date();
        SimpleDateFormat df=new SimpleDateFormat("HH");
        String curTime=df.format(curdate);
        if(Integer.parseInt(curTime)>8 && Integer.parseInt(curTime)<12){
            requestData(1);  //请求数据
        }else if(Integer.parseInt(curTime)>=12 && Integer.parseInt(curTime)<15){
            requestData(2);  //请求数据
        }else if(Integer.parseInt(curTime)>=15 && Integer.parseInt(curTime)<18){
            requestData(3);  //请求数据
        }else if(Integer.parseInt(curTime)>=20 && Integer.parseInt(curTime)<24){
            requestData(4);  //请求数据
        }else {
            requestData(0);  //请求数据
        }
        }catch (Exception e){

        }
    }

    private void requestData(final int index) {
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(LimitTimeGoActivity.this, "没有可用的网络", Toast.LENGTH_SHORT).show();
        } else {
            empty.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback callback=new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    empty.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    LimitBean bean=gson.fromJson(response,LimitBean.class);
                    if(bean.getResult().equals("OK")){

                    Date da = new Date();
                    SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");
                    now=df.format(da);
                    scrollIndicatorView.setBackgroundResource(R.mipmap.blimit);
                    scrollIndicatorView.setScrollBar(new DrawableBar(LimitTimeGoActivity.this, R.mipmap.olimit, ScrollBar.Gravity.CENTENT_BACKGROUND) {
                        @Override
                        public int getHeight(int tabHeight) {
                            return tabHeight;
                        }

                        @Override
                        public int getWidth(int tabWidth) {
                            return tabWidth;
                        }
                    });
                    unSelectTextColor = Color.WHITE;
                    // 设置滚动监听
                    scrollIndicatorView.setOnTransitionListener(new OnTransitionTextListener().setColor(Color.WHITE, unSelectTextColor));
                    indicatorViewPager = new IndicatorViewPager(scrollIndicatorView, viewPager);

                    inflate = LayoutInflater.from(getApplicationContext());
                    scrollIndicatorView.setSplitAuto(true);
                    indicatorViewPager.setPageOffscreenLimit(bean.getPromotionList().size() - 1);//设置保存状态的Fragment数量
                    indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), bean.getPromotionList()));


                    scrollIndicatorView.setCurrentItem(index);
                    viewPager.setCurrentItem(index);
                    }else{
                        Toast.makeText(LimitTimeGoActivity.this, bean.getResult(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                    empty.setErrorType(EmptyLayout.NODATA_ENABLE_CLICK);
                }
            };
            String params="addrId="+AppConfig.CITY_ID;
            OKUtilAPI.post(OKUtilAPI.limitGo,params,callback);

        }
    }


    @Override
    public void initData() {
//        initnFormation();//button 的初始化,数据联网获得
//        initFragment();
//        newRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId) {
//                    case R.id.timebutton_one:
//                        showFragment(timeOneFragment);
//                        break;
//                    case R.id.timebutton_two:
//                        showFragment(timeTwoFragment);
//                        break;
//                    case R.id.timebutton_third:
//                        showFragment(timeThirdFragment);
//                        break;
//                    case R.id.timebutton_four:
//                        showFragment(timeFourFragment);
//                        break;
//                    case R.id.timebutton_five:
//                        showFragment(timeFiveFragment);
//                        break;
//                }
//            }
//        });

    }

    private void initFragment() {
        timeOneFragment = new TimeOneFragment();
        timeTwoFragment = new TimeTwoFragment();
        timeThirdFragment = new TimeThirdFragment();
        timeFourFragment = new TimeFourFragment();
        timeFiveFragment = new TimeFiveFragment();

        fragmentManager = getSupportFragmentManager();
        currentFragment = timeOneFragment;
//            showFragment(timeOneFragment);

    }

    private void initnFormation() {
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(LimitTimeGoActivity.this, "没有可用的网络", Toast.LENGTH_SHORT).show();
        } else {
            empty.setErrorType(EmptyLayout.NETWORK_LOADING);
            JsonHttpNet.dataDownNet(OKUtilAPI.limitGo + "?addrId=" + AppConfig.CITY_ID, new JsonHttpNet.HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    empty.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    Log.e("URLTEMP", "-----" + response);
                    try {
                        JSONObject object = new JSONObject(response);
                        JSONArray promotionList = object.getJSONArray("promotionList");
                        for (int i = 0; i < promotionList.length(); i++) {
                            switch (i) {
                                case 0:
                                    JSONObject promotionJSONObject = promotionList.getJSONObject(0);
                                    String titles = promotionJSONObject.getString("title");
                                    String end1=promotionJSONObject.getString("end");
                                    String id = promotionJSONObject.getString("id");//传相应的id
                                    AppConfig.ID_ONE = id;
                                    Log.e("RR", "title1:=========" + titles);
                                    Date now = new Date();
                                    SimpleDateFormat df=new SimpleDateFormat("HH:mm");
                                    String hour1=df.format(now);
//                                    String hour1 = now.getHours() + "" + now.getMinutes();//取当前时间的小时.
                                    String result1 = StringUtils.timeCompare(hour1, titles,end1);
                                    AppConfig.RESULTONE = result1;
                                    if (result1.equals("已结束")) {
                                        timebuttonOne.setText(titles + "\n" + result1);
                                        limit_out.setVisibility(View.VISIBLE);
                                        limittime.setVisibility(View.GONE);
                                        curIndex1=0;
                                    } else if(result1.equals("抢购中")){
                                        limit_out.setVisibility(View.GONE);
                                        limittime.setVisibility(View.VISIBLE);
                                        timebuttonOne.setText(titles + "\n" + result1);
                                        curIndex1=1;
                                    }else {
                                        timebuttonOne.setText(titles + "\n" + result1);
                                        curIndex1=0;
                                    }
                                    break;
                                case 1:
                                    JSONObject promotionJSONObject1 = promotionList.getJSONObject(1);
                                    String title1 = promotionJSONObject1.getString("title");
                                    String id1 = promotionJSONObject1.getString("id");
                                    String end2=promotionJSONObject1.getString("end");


                                    String hosu=title1.substring(0, title1.indexOf(":"));
                                    String misn=title1.substring(title1.indexOf(":") + 1);
                                    AppConfig.ID_TWO = id1;
                                    Log.e("RR", "title2-------------" + title1);
                                    Date now1 = new Date();
//                                    String hour2 = now1.getHours() + "" + now1.getMinutes();//取当前时间的小时.
                                    SimpleDateFormat df2=new SimpleDateFormat("HH:mm");
                                    String hour2=df2.format(now1);
                                    String result2 = StringUtils.timeCompare(hour2, title1,end2);
                                    AppConfig.RESULTTWO = result2;
                                    if (result2.equalsIgnoreCase("已结束")) {
                                        timebuttonTwo.setText(title1 + "\n" + result2);
                                        curIndex2=0;
                                    } else if(result2.equalsIgnoreCase("抢购中")){
                                        timebuttonTwo.setText(title1 + "\n" + result2);
                                        curIndex2=1;
                                    }else {
                                        timebuttonTwo.setText(title1 + "\n" + result2);
                                        curIndex2=0;
                                    }
                                    break;

                                case 2:
                                    JSONObject promotionJSONObject2 = promotionList.getJSONObject(2);
                                    String title2 = promotionJSONObject2.getString("title");
                                    String end3=promotionJSONObject2.getString("end");
                                    String id2 = promotionJSONObject2.getString("id");
                                    AppConfig.ID_THREE = id2;
                                    Log.e("RR", "title3-------------" + title2);
                                    Date now2 = new Date();
                                    SimpleDateFormat df3=new SimpleDateFormat("HH:mm");
                                    String hour3=df3.format(now2);
                                    String result3 = StringUtils.timeCompare(hour3, title2,end3);
                                    AppConfig.RESULTTHREE = result3;
                                    if (result3.equalsIgnoreCase("已结束")) {
                                        timebuttonThird.setText(title2 + "\n" + result3);
                                        curIndex3=0;
                                    } else if(result3.equalsIgnoreCase("抢购中")){
                                        curIndex3=1;
                                        timebuttonThird.setText(title2 + "\n" + result3);
                                    }else {
                                        timebuttonThird.setText(title2 + "\n" + result3);
                                        curIndex3=0;
                                    }
                                    break;
                                case 3:
                                    JSONObject promotionJSONObject3 = promotionList.getJSONObject(3);
                                    String title4 = promotionJSONObject3.getString("title");
                                    String end4=promotionJSONObject3.getString("end");
                                    String id3 = promotionJSONObject3.getString("id");
                                    Log.e("RR", "title4-------------" + title4);
                                    AppConfig.ID_FOUR = id3;
                                    Date now3 = new Date();
                                    SimpleDateFormat df4=new SimpleDateFormat("HH:mm");
                                    String hour4=df4.format(now3);
                                    String result4 = StringUtils.timeCompare(hour4, title4,end4);
                                    AppConfig.RESULTFOUR = result4;
                                    if (result4.equalsIgnoreCase("已结束")) {
                                        timebuttonFour.setText(title4 + "\n" + result4);
                                        limit_out.setVisibility(View.VISIBLE);
                                        limittime.setVisibility(View.GONE);
                                        curIndex4=0;
                                    } else if(result4.equalsIgnoreCase("抢购中")){
                                        timebuttonFour.setText(title4 + "\n" + result4);
                                        limit_out.setVisibility(View.GONE);
                                        limittime.setVisibility(View.VISIBLE);
                                        curIndex4=1;
                                    }else {
                                        timebuttonFour.setText(title4 + "\n" + result4);
                                        curIndex4=0;
                                    }
                                    break;
                                case 4:
                                    JSONObject promotionJSONObject4 = promotionList.getJSONObject(4);
                                    String title5 = promotionJSONObject4.getString("title");
                                    String end5=promotionJSONObject4.getString("end");
                                    String id4 = promotionJSONObject4.getString("id");
                                    AppConfig.ID_FIVE = id4;
                                    Date now4 = new Date();
                                    SimpleDateFormat df5=new SimpleDateFormat("HH:mm");
                                    String hour5=df5.format(now4);
                                    String result5 = StringUtils.timeCompare(hour5, title5,end5);
                                    AppConfig.RESULTFIVE = result5;
                                    if (result5.equalsIgnoreCase("已结束")) {
                                        timebuttonFive.setText(title5 + "\n" + result5);
                                        limit_out.setVisibility(View.VISIBLE);
                                        limittime.setVisibility(View.GONE);
                                        curIndex5=0;
                                    } else if(result5.equalsIgnoreCase("抢购中")){
                                        timebuttonFive.setText(title5 + "\n" + result5);
                                        limit_out.setVisibility(View.GONE);
                                        limittime.setVisibility(View.VISIBLE);
                                        curIndex5=1;
                                    }else {
                                        timebuttonFive.setText(title5 + "\n" + result5);
                                        curIndex5=0;
                                    }
                                    break;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Exception e) {
                    empty.setErrorType(EmptyLayout.NODATA);
                    // Toast.makeText(TimeGoActivity.this, "网络加载失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

//    private void showFragment(Fragment targetFragment) {
//        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//        if (!targetFragment.isAdded()) {
//            fragmentTransaction.add(R.id.timeFrame, targetFragment).hide(currentFragment).show(targetFragment).commit();
//        } else {
//            fragmentTransaction.hide(currentFragment).show(targetFragment).commit();
//        }
//        currentFragment = targetFragment;
//
//    }

    @Override
    protected void onResume() {
        super.onResume();
//        startRun();
    }

    public static int gettime(String star, String end, String sys) {
        java.text.DateFormat df = new java.text.SimpleDateFormat("HH:mm:ss");
        java.util.Calendar c1 = java.util.Calendar.getInstance();
        java.util.Calendar c2 = java.util.Calendar.getInstance();
        java.util.Calendar c3 = java.util.Calendar.getInstance();
        try {
            c1.setTime(df.parse(star));
            c2.setTime(df.parse(sys));
            c3.setTime(df.parse(end));
        } catch (java.text.ParseException e) {
            System.err.println("时间格式不正确");
        }
        int result = -1;
        if (c1.compareTo(c2) > 0) {
            result = 0;
        } else if (c1.compareTo(c2) <= 0 && c2.compareTo(c3) <= 0) {
            result = 1;
        } else if (c2.compareTo(c3) > 0) {
            result = 2;
        }
        return result;
    }
    private class MyAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {
        List<LimitBean.Limit> list;

        public MyAdapter(FragmentManager fragmentManager, List<LimitBean.Limit> list) {
            super(fragmentManager);
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = inflate.inflate(R.layout.tab_top, container, false);
            }
            TextView textView = (TextView) convertView;

            switch (gettime(list.get(position).getStart() + ":00", list.get(position).getEnd() + ":59", now)) {
                case 0:
                    textView.setText(list.get(position).getTitle() + "\n" + "未开抢");
                    break;
                case 1:
                    textView.setText(list.get(position).getTitle() + "\n" + "抢购中");
                    break;
                case 2:
                    textView.setText(list.get(position).getTitle() + "\n" + "已结束");
                    break;
            }
            int padding = DensityUtils.dp2px(getBaseContext(), 10);
            textView.setPadding(padding, 0, padding, 0);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {


//            if(TDevice.isTablet(LimitTimeGoActivity.this)){
//                //ATM
//                TimeOneFragment fragment = new TimeOneFragment();
//                Bundle bundle = new Bundle();
//                bundle.putString("actid", list.get(position).getId() + "");
//                bundle.putString("starttime", list.get(position).getStart() + ":00");
//                bundle.putString("endtime", list.get(position).getEnd() + ":59");
//                bundle.putString("now", now);
//                bundle.putInt("position", position);
//                fragment.setArguments(bundle);
//
//                return fragment;
//
//            }else{
//                //APP
                TimeOneFragment fragment = new TimeOneFragment();
                Bundle bundle = new Bundle();
                bundle.putString("actid", list.get(position).getId() + "");
                bundle.putString("starttime", list.get(position).getStart() + ":00");
                bundle.putString("endtime", list.get(position).getEnd() + ":59");
                bundle.putString("now", now);
                bundle.putInt("position", position);
                fragment.setArguments(bundle);

                return fragment;

//            }

        }

        @Override
        public int getItemPosition(Object object) {
            //这是ViewPager适配器的特点,有两个值 POSITION_NONE，POSITION_UNCHANGED，默认就是POSITION_UNCHANGED,
            // 表示数据没变化不用更新.notifyDataChange的时候重新调用getViewForPage
            return PagerAdapter.POSITION_NONE;
        }

    }


    @Override
    public int getContentViewId() {
        return R.layout.activity_limtit_go;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }

}
